<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-calendar"></i>xx管理</el-breadcrumb-item>
                <el-breadcrumb-item>编辑</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

		<div class="container">
			<el-row>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form ref="form" :model="form" label-width="100px">

<?php 
use yii\helpers\StringHelper;
$tableSchema = $generator->getTableSchema();
$controllerClass = StringHelper::basename($generator->controllerClass);
$controller = str_replace('Controller', '', $controllerClass);
$controller = lcfirst($controller);
$controller = toUnderScore1($controller);

//驼峰命名转中划线命名
function toUnderScore1($str)
{
  $dstr = preg_replace_callback('/([A-Z]+)/', function($matchs)
  {
      return '-'.strtolower($matchs[0]);
  },$str);
  return trim(preg_replace('/-{2,}/','-',$dstr),'-');
}

$isImg = false;
$isHaveImg = false;
$jsonArr = [];
$isEditor = false;
foreach ($tableSchema->columns as $column): ?>
<?php

    $prop = $column->name;
    $label = $column->comment ? $column->comment : strtoupper($column->name);
    if(in_array($prop, ['id', 'create_time', 'update_time'])) continue;

    $mult = false;
    $isImg = false;
    $stateListArr = [];

    $match = '/(img)|(image)|(logo)|(pic)|(picture)/';
    if(preg_match($match, $prop)){
        $isImg = true;
        $isHaveImg = true;
    }

    $match = '/(imgs)|(images)|(pics)|(pictures)/';
    if(preg_match($match, $prop)){
        $mult = true;
        $isHaveImg = true;
        $jsonArr[] = $prop;
    }

    if((strpos($column->comment, 'json') !== false) && !in_array($prop, $jsonArr)) {
        $jsonArr[] = $prop;
    }

       
        if($prop == 'state') 
        {
            $stateListArr['field'] = $column->name;
            $stateTextArr = explode(":",  $column->comment);
            if(count($stateTextArr) <= 1) continue;
            $stateName = $stateTextArr['0'];
            $stateValArr = explode(',', $stateTextArr[1]);
            $stateListArr['name'] = $stateName;

            foreach($stateValArr as $valArr) {
                $tmpValArr = explode('=', $valArr);
                if(count($tmpValArr) < 2) continue;
                $key = $tmpValArr[0];
                $value = $tmpValArr[1];
                $stateListArr['data'][] = ['key' => $key, 'value' => $value];
            }
        }

    if($mult){
?>
                        <el-form-item label="<?=$label?>">
                            <upload :isMult="true" @selectImg="showImg" :imgModel="'<?=$prop?>'" :initData="arrData.<?=$prop?>"></upload>
                        </el-form-item>
<?php } else if($isImg){?>
                        <el-form-item label="<?=$label?>">
                            <upload :isMult="false" @selectImg="showImg" :imgModel="'<?=$prop?>'" :initData="form.<?=$prop?>"></upload>
                        </el-form-item>

<?php } else if($stateListArr && !empty($stateListArr['data'])) {?>
                        <el-form-item label="<?=$label?>">
<?php foreach($stateListArr['data'] as $val) {?>
                            <el-radio v-model="form.<?=$prop?>" label="<?=$val['key']?>"><?=$val['value']?></el-radio>
<?php }?>
                        </el-form-item>    
<?php } else if($prop == 'content'){ $isEditor = true; ?>
                        <el-form-item label="<?=$label?>">
                            <editor @getContent="getContent" :initContent="form.<?=$prop?>"></editor>
                        </el-form-item>    
<?php } else {?>
						<el-form-item label="<?=$label?>">
							<el-input v-model="form.<?=$prop?>" placeholder="请输入<?=$label?>"></el-input>
						</el-form-item>
<?php } endforeach; ?>
                        <el-form-item label="">
                            <el-button :loading="loading" type="primary" @click="saveData">保存</el-button>
                        </el-form-item>
					</el-form>
				</el-col>
			</el-row>
		</div>
	</div>
</template>

<script type="text/javascript">
<?php if($isHaveImg) {?>
    import upload from '@/components/utils/upload';
<?php }?>
<?php if($isEditor) {?>
    import editor from '@/components/utils/editor';
<?php }?>
	export default{
        components: {
<?php if($isHaveImg) {?> 
            upload,
<?php }?>
<?php if($isEditor) {?>
    editor
<?php }?>
        },
		data() {
			return {
				loading: false,
				id: '',
				form:{
<?php foreach ($tableSchema->columns as $column):
			
		if(in_array($column->name, ['create_time', 'update_time'])) continue;
?>
                    <?=$column->name?>: '',
<?php endforeach; ?>

                },
<?php if($jsonArr) {?>
                arrData:{
<?php 
    foreach($jsonArr as $jsonKey) {
echo "                    ".$jsonKey. ":[],\r\n";
    }
?>
                }
<?php }?>
			}
		},
		created() {
            this.id = this.$route.query.id;
			this.getData();

		},
		methods: {
			getData() {
                if(this.id <= 0) return;
                this.loading = true;
                let param = {id: this.id};
                this.$post_('<?=$controller?>/info', param, (res) => {
                    this.loading = false;
                    if(res.code == 0 && res.data) {
<?php foreach ($tableSchema->columns as $column): 
		if(in_array($column->name, ['create_time', 'update_time'])) continue;
?>
                        this.form.<?=$column->name?> = res.data.<?=$column->name?>;
<?php endforeach; ?>
<?php 
    if($jsonArr){
        foreach($jsonArr as $jsonKey){
            echo "                        this.arrData.".$jsonKey." = JSON.parse(res.data.".$jsonKey.");\r\n";
        }
    }
?>
                    }
                }, (res) => {
                    this.loading = false;
                })
			},

<?php if($isHaveImg){ ?>

            showImg(imgData, isMult, imgKey) {
                if(isMult) {
                    this.arrData[imgKey] = [];
                    imgData.forEach((val) => {
                        this.arrData[imgKey].push(val);
                    })
                }else{
                    this.form[imgKey] = imgData;
                }
            },                      
<?php }?>
<?php if($isEditor) {?>
            //获取编辑器内容
            getContent(content) {
                this.form.content = content;
            },
<?php }?> 

            //保存数据
            saveData() {
                this.loading = true;
                this.form.id = this.id;
<?php
    if($jsonArr){
        foreach($jsonArr as $jsonKey){
            echo "                this.form.".$jsonKey. " = JSON.stringify(this.arrData.".$jsonKey.");\r\n";
        }
    }
?>

                this.$post_('<?=$controller?>/edit', this.form, (res) => {
                    console.log(res);
                    this.loading = false;
                    if(res.code == 0){
                        this.$message.success(res.msg);
                        this.$router.back(-1);
                    }else{
                        this.$message.error(res.msg);
                    }
                }, (res) => {
                	this.loading = false;
                	this.$message.error('出错了！')
                })
            }
		}
	}
</script>

<style scoped="scoped">

</style>